package br.ufrj.dcc.recinfo.bullsearch.lucene;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.NumericField;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class LuceneSearch {
	private static final String indexPath = "index";
	
	public void search(String q) throws IOException, ParseException{
		Directory fsdir = FSDirectory.open(new File(indexPath));
		IndexSearcher searcher = new IndexSearcher(fsdir);
		
		QueryParser parser = new QueryParser(Version.LUCENE_33, "contents", new StandardAnalyzer(Version.LUCENE_33));
		
		Query query = parser.parse(q);
		
		// Pesquisa e informa quantidade de documentos retornados
	    TopDocs results = searcher.search(query, 2);
	    System.out.println("Total de documentos no resultado: " + results.totalHits);

	    
	    // Mostra data de modificação e caminho de cada documento que satisfez a consulta
	    ScoreDoc[] hits = results.scoreDocs;
	    for (int i = 0; i < hits.length; i++) {

	    	// Obtem documento
	    	Document doc = searcher.doc(hits[i].doc);

	    	// Obtem campo numerico e converte para data/hora
	    	NumericField fld = (NumericField) doc.getFieldable("modified");
	    	long t = fld.getNumericValue().longValue();
	    	Date modifiedDate = new Date(t);
	    	
	    	// Obtem valor de campo textual
	    	String path = doc.get("path");
	    	
	    	// Apresenta resultado
	    	System.out.println(
	    			DateFormat.getDateTimeInstance().format(modifiedDate) + "\t" +
	    			String.format("%4.1f%%", (100*hits[i].score)) + "\t" +
	    			path);
	    }	    
		
		// Fecha
		searcher.close();
	}

}
